﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows.Navigation;
using GalaSoft.MvvmLight.Command;
using MishraReader.Entities;
using MishraReader.Entities.ShareServices;
using MishraReader.Services;
using MishraReader.ViewModels.Base;
using MetroLog;

namespace MishraReader.ViewModels.Settings.Options
{
    public class TwitterConfigurationViewModel : DialogViewModelBase, IShareServiceConfigurationViewModel
    {
        private static readonly ILogger Log = LogManagerFactory.DefaultLogManager.GetLogger<TwitterConfigurationViewModel>();
        private readonly IWpfApplication _application;
        private readonly IErrorService _errorService;
        private readonly ITwitterApi _twitterApi;
        private Uri _loginUri;

        private bool _userInputRequired;

        public TwitterConfigurationViewModel(IErrorService errorService,
                                             ITwitterApi twitterApi, IWpfApplication application) 
        {
            _errorService = errorService;
            _twitterApi = twitterApi;
            _application = application;

            _twitterApi.ConsumerKey = TwitterShareService.ConsumerKey;
            _twitterApi.ConsumerKeySecret = TwitterShareService.ConsumerKeySecret;
            _twitterApi.CallbackUri = TwitterShareService.CallbackUri;

            NavigatingCommand = new RelayCommand<NavigatingCancelEventArgs>(OnNavigated);
        }

        public Uri LoginUri
        {
            get { return _loginUri; }
            private set
            {
                Set(ref _loginUri, value);
            }
        }

        public ICommand NavigatingCommand { get; private set; }
        public IServiceAccountViewModel ServiceAccountViewModel { get; set; }

        public bool UserInputRequired
        {
            get { return _userInputRequired; }
            private set
            {
                Set(ref _userInputRequired, value);
            }
        }

        public async void Configure()
        {
            var uri = await _twitterApi.GetAuthorizationUriAsync();

            ShowData = true;
            LoginUri = uri;
            UserInputRequired = true;
        }

        public void Disconnect()
        {
            Reset();
        }

        protected override void OnDialogClosed(bool? result)
        {
            base.OnDialogClosed(result);

            Reset();
        }

        private async void OnNavigated(NavigatingCancelEventArgs e)
        {
            try
            {
                ITwitterAuthorization result;
                if (_twitterApi.IsSuccessful(e.Uri, out result))
                {
                    e.Cancel = true;
                    UserInputRequired = false;

                    try
                    {
                        if (result.IsAuthenticated) // got an auth but no tokens means the user hit cancel
                        {
                            var token = await _twitterApi.TranslateAuthorizationToTokenAsync(result);

                            ServiceAccountViewModel.ServiceUserName = token.ScreenName;
                            ServiceAccountViewModel.ServicePassword = token.TokenSecret;
                            ServiceAccountViewModel.SaveChangesToken(token.Token);
                            ServiceAccountViewModel.IsActivated = true;

                            ExecuteOkayCommand();
                            
                        }
                        else
                        {
                            ExecuteCancelCommand();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("WebBrowserNavigated", ex);
                        _errorService.HandleException(ex);
                    }
                }
                else
                {
                    UserInputRequired = true;
                }
            }
            catch (Exception ex)
            {
                Log.Error("WebBrowserNavigated", ex);
                _errorService.HandleException(ex);
            }
        }

        private void Reset()
        {
            UserInputRequired = true;
            LoginUri = null;
        }
    }
}